package com.hellowx.manager.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellowx.manager.pojo.Goods;
import com.hellowx.manager.service.GoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author MagicMushroom
 * @date 2021/7/17
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Resource
    private GoodsService goodsService;

    /**
     *  保存商品
     * @param goods 商品对象
     * @return map
     */
    @RequestMapping("/save")
    public Map<String,Object> save(String goods){
        Goods goodsObject = JSON.parseObject(goods,Goods.class);
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String onTime = dateFormat.format(date);
        goodsObject.setOnTime(Integer.valueOf(onTime));
        System.out.println(goodsObject);
        Map<String, Object> map= new HashMap<>();
        Integer goodsId=-1;
        try{
            goodsId = goodsService.save(goodsObject);
        }catch (Exception e){
            e.printStackTrace();
            map.put("goodsId",goodsId);
            map.put("msg","输入信息有误!!");
            return map;
        }

        map.put("goodsId",goodsId);
        if (goodsId!=-1){
            map.put("msg","插入失败");
        }
        map.put("msg","ok!!");
        return map;
    }


    /**
     * 根据条件查询商品
     * @param goods goodsName 商品名称   catId 分类id   brandId 品牌id
     * @param pageIndex pageIndex 分页索引
     * @param pageSize pageSize 分页大小
     * @return 商品列表
     */
    @RequestMapping
    public Map<String, Object> getAll(Goods goods,Integer pageIndex,Integer pageSize){
        IPage<Goods> goodsPage =  new Page<>(pageIndex,pageSize);
        Map<String, Object> map=new HashMap<>();
        map.put("goodsList",goodsService.getAll(goodsPage,goods));
        long totalPage = goodsPage.getTotal()%10==0?goodsPage.getTotal()/pageSize:goodsPage.getTotal()/pageSize+1;
        map.put("totalPage",totalPage);
        return map;
    }
}
